package com.hhf.rpa.menu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hhf.rpa.base.ResponseResult;
import com.hhf.rpa.menu.model.Menu;
import com.hhf.rpa.menu.pojo.dto.MenuTree;
import com.hhf.rpa.menu.pojo.form.MenuForm;
import com.hhf.rpa.menu.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Controller
@RequestMapping(value = "/admin/menu")
public class MenuAdminController {
    @Autowired
    private MenuService menuService;

    @GetMapping
    public String menu(HttpServletRequest request){
        List<MenuTree> menuTree = menuService.getMenuTree();
        request.setAttribute("menuTree",menuTree);
        return "/menu";
    }

    @GetMapping("/getMenuPage")
    public String getMenuPage(HttpServletRequest request, MenuForm form){
        IPage<List<Menu>> page = menuService.getMenuPage(form);
        request.setAttribute("page",page);
        return "/menuPage";
    }

    @GetMapping("/menuEdit")
    public String menuEdit(HttpServletRequest request, Long menuId){
        Menu menu = new Menu();
        if(menuId != null) {
            menu = menuService.getById(menuId);
        }
        request.setAttribute("menu", menu);
        return "/menuEdit";
    }

    @PostMapping("/saveMenu")
    public String saveMenu(Menu menu) {
        menuService.saveMenu(menu);
        return "redirect:/admin/menu/getMenuPage";
    }
    @ResponseBody
    @PostMapping("/delMenu")
    public ResponseResult delMenu(HttpServletRequest request, String menuId){
        menuService.removeById(menuId);
        MenuForm menu = new MenuForm();
        IPage<List<Menu>> page = menuService.getMenuPage(menu);
        request.setAttribute("page", page);
        return ResponseResult.success();
    }

    @GetMapping("/getMenuTree")
    @ResponseBody
    public List<MenuTree> getMenuTree(){
        List<MenuTree> allMenu = menuService.getMenuTree();
        return allMenu;
    }
}
